package cn.nucun.frame;

import cn.nucun.base.WindowsRem;
import cn.nucun.entity.constant.SocketConstant;
import cn.nucun.entity.po.Message;
import cn.nucun.factory.ToolWindowsFactory;
import cn.nucun.utils.PlugsUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.neovisionaries.ws.client.*;
import org.apache.commons.lang.StringUtils;

import javax.swing.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import static cn.nucun.entity.constant.SocketConstant.HttpRequest.REQ_WS_CONNECT;
import static cn.nucun.entity.constant.SocketConstant.Message.*;
import static cn.nucun.entity.constant.SocketConstant.Systems.SYS_USER_KEY;
import static cn.nucun.utils.DateUtil.localDateTimeFormatAllMate;
import static cn.nucun.utils.DateUtil.toLocalDateTime;

/**
 * @author Administrator
 */
public class MainCreateFrame {

    /**
     * 主要面板
     */
    private JPanel panelMain;
    /**
     * 信息滚动框
     */
    private JTextArea textShow;
    /**
     * 发送按钮
     */
    private JButton sendMyMsg;
    /**
     * 我的消息体
     */
    private JTextArea writeMyMsg;
    /**
     * 我的消息承载面板
     */
    private JPanel writePanel;
    /**
     * 让面板滚动
     */
    private JScrollPane textScroll;

    /**
     * socket
     */
    private WebSocket websocket;


    public MainCreateFrame() {
        if (PlugsUtils.checkLogin()) {
            try {
                if (websocket == null) {
                    init();
                }
                listener();
            } catch (IOException e) {
                if (websocket != null) {
                    websocket.disconnect();
                }
                PlugsUtils.modalMessageError("通讯连接异常，请重试.:" + e.getMessage());
            }
        } else {
            textShow.setText("请先登录");
            new ToolWindowsFactory().tryClose();
        }
    }

    /**
     * 初始化
     */
    private void init() throws IOException {
        websocket = new WebSocketFactory()
                .setConnectionTimeout(6000)
                .createSocket(REQ_WS_CONNECT + WindowsRem.MY)
                .addListener(new WebSocketAdapter() {
                    @Override
                    public void onTextMessage(WebSocket ws, String message) {
                        Message msg = JSONObject.parseObject(message, Message.class);
                        if (msg != null) {
                            switch (msg.getTo()) {
                                case SocketConstant.MegType.MT_TYPE_ONE_LOGIN:
                                    msg.setFrom(msg.getText());
                                    msg.setText("已经上线");
                                    break;
                                case SocketConstant.MegType.MT_TYPE_ONE_LOGOUT:
                                    msg.setFrom(msg.getText());
                                    msg.setText("已经离开");
                                    break;
                                default:
                                    if (msg.getTo().equals(WindowsRem.MY)) {
                                        msg.setFrom("收到" + msg.getFrom() + "私信");
                                    }
                            }
                            textShow.append(String.format("%s-%s:%s \n", localDateTimeFormatAllMate(toLocalDateTime(msg.getDate())), msg.getFrom(), msg.getText()));
                        } else {
                            PlugsUtils.warnNotify("接收消息失败", null);
                        }
                    }

                    @Override
                    public void onConnected(WebSocket websocket, Map<String, List<String>> headers) throws Exception {
                        super.onConnected(websocket, headers);
                    }

                    @Override
                    public void onConnectError(WebSocket websocket, WebSocketException exception) throws Exception {
                        //清除登录信息
                        System.clearProperty(SYS_USER_KEY);
                        //清除浮窗
                        new ToolWindowsFactory().tryRemove();
                        super.onConnectError(websocket, exception);
                    }

                    @Override
                    public void onDisconnected(WebSocket websocket, WebSocketFrame serverCloseFrame, WebSocketFrame clientCloseFrame, boolean closedByServer) throws Exception {
                        //清除浮窗
                        new ToolWindowsFactory().tryRemove();
                        super.onDisconnected(websocket, serverCloseFrame, clientCloseFrame, closedByServer);
                    }
                })
                .connectAsynchronously();
    }

    /**
     * 监听器
     */
    private void listener() {
        //监听键盘回车事件
        writeMyMsg.addKeyListener(new KeyAdapter() {
            @Override
            public void keyTyped(KeyEvent e) {
                if (e.getKeyChar() == KeyEvent.VK_ENTER) {
                    //回车键
                    doSend();
                }
            }
        });
        //监听发送按钮的点击事件
        sendMyMsg.addActionListener(e -> doSend());
    }

    /**
     * 发送网络消息并上屏
     */
    private void doSend() {
        if (PlugsUtils.checkLogin()) {
            String myMsg = writeMyMsg.getText().trim();
            if (StringUtils.isEmpty(myMsg)) {
                PlugsUtils.modalMessageWarn("请输入发送内容！");
            } else {
                Message message = new Message(myMsg);
                if (myMsg.startsWith(SPECIAL_TAG_SEND_TO_SOMEBODY)) {
                    String[] split = myMsg.split(SPECIAL_TAG_SEND_TO_SOMEBODY);
                    if (split.length > 2 && StringUtils.isNotEmpty(split[2])) {
                        //给某人发消息
                        message.setTo(split[1]);
                        message.setText(split[2]);
                        writeMyMsg.setText("@" + split[1] + "@");
                        textShow.append(String.format("发送给-%s:%s \n", message.getTo(), message.getText()));
                    } else {
                        message.setText(null);
                        //清除已经发送的内容
                        writeMyMsg.setText(null);
                    }
                } else if (myMsg.startsWith(SPECIAL_TAG_LOGIN_OUT)) {
                    WindowsRem.MY = null;
                    websocket.disconnect();
                    textShow.setText("请先登录");
                    new ToolWindowsFactory().tryClose();
                    //清除已经发送的内容
                    writeMyMsg.setText(null);
                } else if (myMsg.startsWith(SPECIAL_TAG_PLUGS_OUT)) {
                    textShow.setText("请先登录");
                    WindowsRem.MY = null;
                    websocket.disconnect();
                    new ToolWindowsFactory().tryRemove();
                    //清除已经发送的内容
                    writeMyMsg.setText(null);
                }else{
                    //清除已经发送的内容
                    writeMyMsg.setText(null);
                }
                if (websocket != null && message.getText() != null) {
                    //网络同步
                    websocket.sendText(JSON.toJSONString(message, true));
                }
            }
        }
    }


    /**
     * 窗体获取我的定义模块
     *
     * @return 我的主面板
     */
    public JPanel getPanel() {
        return panelMain;
    }
}
